package com.baizhi.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class UserController {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource  //负载均衡的客户端对象
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate restTemplate;


    @GetMapping("user")
    public String invokeDemo() {
//        第一种
//        String forObject = restTemplate.getForObject("http://" + randomHost() + "/order", String.class);
        //使用ribbon组件实现负载均衡调用 DiscoveryClient 或者LoadBalanceClient @LoadBalancer
//        List<ServiceInstance> orders = discoveryClient.getInstances("ORDERS");
//        for (ServiceInstance order : orders) {
//            log.info("服务主机:[{}] 服务端口[{}],服务地址:[{}]", order.getHost(), order.getPort(), order.getUri());
//        }
//        String forObject = restTemplate.getForObject(orders.get(0).getUri() + "/order", String.class);

        //第二种使用loadBalancerClient  轮询策略
//        ServiceInstance order = loadBalancerClient.choose("ORDERS");
//        log.info("服务主机:[{}] 服务端口[{}],服务地址:[{}]", order.getHost(), order.getPort(), order.getUri());
//        String forObject = restTemplate.getForObject(order.getUri() + "/order", String.class);
//        log.info("调用接口[{}]", forObject);
//        第三种使用@LoadBalanced 让对象具有ribbon负载均衡特性
        String result = restTemplate.getForObject("http://ORDERS/order", String.class);
        return "ok"+result;
    }

    public String randomHost() {
        List<String> hosts = new ArrayList<>();
        hosts.add("localhost:9999");
        hosts.add("localhost:9990");
        //生成随机数
        int i = new Random().nextInt(hosts.size());
        System.out.println(i);
        return hosts.get(i);
    }

}
